package com.tanger.common.utils;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 当前用户信息工具类
 */
public class CurrentUserUtils {

	private CurrentUserUtils() {

	}

	/**
	 * 获取当前用户详情信息
	 * 
	 * @return
	 */
	public static Map<String, String> getAuthenticationDetails() {
		Map<String, String> oauth2AuthenticationMap = null;
		try {
			oauth2AuthenticationMap = new HashMap<>();
			OAuth2Authentication oauth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
			UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) oauth2Authentication
					.getUserAuthentication();
			String tenantCode = (String) ((LinkedHashMap<?, ?>) ((LinkedHashMap<?, ?>) ((LinkedHashMap<?, ?>) usernamePasswordAuthenticationToken.getDetails())
					.get("userAuthentication")).get("details")).get("tenantCode");
			oauth2AuthenticationMap.put("name", oauth2Authentication.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oauth2AuthenticationMap;
	}

	/**
	 * 获取当前用户信息
	 * 
	 * @return
	 */
	public static Map<String, String> getAuthenticationInfo() {
		Map<String, String> oauth2AuthenticationMap = null;
		try {
			oauth2AuthenticationMap = new HashMap<>();
			OAuth2Authentication oauth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
			UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) oauth2Authentication
					.getUserAuthentication();
			String id = (String) ((LinkedHashMap<?, ?>) usernamePasswordAuthenticationToken.getDetails()).get("id");
			String userName = (String) ((LinkedHashMap<?, ?>) usernamePasswordAuthenticationToken.getDetails()).get("name");
			String roleType = (String) ((LinkedHashMap<?, ?>) usernamePasswordAuthenticationToken.getDetails()).get("roleType");
			String mobile = (String) ((LinkedHashMap<?, ?>) usernamePasswordAuthenticationToken.getDetails()).get("mobile");
			oauth2AuthenticationMap.put("name", oauth2Authentication.getName());
			oauth2AuthenticationMap.put("id", id);
			oauth2AuthenticationMap.put("userName", userName);
			oauth2AuthenticationMap.put("roleType", roleType);
			oauth2AuthenticationMap.put("mobile", mobile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oauth2AuthenticationMap;
	}

}
